home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Class / Struct.pm
Encoding:
Perl POD Document  |  1999-12-28  |  12.0 KB  |  435 lines

  1. package Class::Struct;
  2.  
  3.  
  4. require 5.002;
  5.  
  6. use strict;
  7. use vars qw(@ISA @EXPORT);
  8.  
  9. use Carp;
  10.  
  11. require Exporter;
  12. @ISA = qw(Exporter);
  13. @EXPORT = qw(struct);
  14.  
  15. my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
  16.  
  17. my $print = 0;
  18. sub printem {
  19.     if (@_) { $print = shift }
  20.     else    { $print++ }
  21. }
  22.  
  23. {
  24.     package Class::Struct::Tie_ISA;
  25.  
  26.     sub TIEARRAY {
  27.         my $class = shift;
  28.         return bless [], $class;
  29.     }
  30.  
  31.     sub STORE {
  32.         my ($self, $index, $value) = @_;
  33.         Class::Struct::_subclass_error();
  34.     }
  35.  
  36.     sub FETCH {
  37.         my ($self, $index) = @_;
  38.         $self->[$index];
  39.     }
  40.  
  41.     sub DESTROY { }
  42. }
  43.  
  44. sub struct {
  45.  
  46.  
  47.     my ($class, @decls);
  48.     my $base_type = ref $_[1];
  49.     if ( $base_type eq 'HASH' ) {
  50.         $class = shift;
  51.         @decls = %{shift()};
  52.         _usage_error() if @_;
  53.     }
  54.     elsif ( $base_type eq 'ARRAY' ) {
  55.         $class = shift;
  56.         @decls = @{shift()};
  57.         _usage_error() if @_;
  58.     }
  59.     else {
  60.         $base_type = 'ARRAY';
  61.         $class = (caller())[0];
  62.         @decls = @_;
  63.     }
  64.     _usage_error() if @decls % 2 == 1;
  65.  
  66.  
  67.     my $isa = do {
  68.         no strict 'refs';
  69.         \@{$class . '::ISA'};
  70.     };
  71.     _subclass_error() if @$isa;
  72.     tie @$isa, 'Class::Struct::Tie_ISA';
  73.  
  74.  
  75.     croak "function 'new' already defined in package $class"
  76.         if do { no strict 'refs'; defined &{$class . "::new"} };
  77.  
  78.     my @methods = ();
  79.     my %refs = ();
  80.     my %arrays = ();
  81.     my %hashes = ();
  82.     my %classes = ();
  83.     my $got_class = 0;
  84.     my $out = '';
  85.  
  86.     $out = "{\n  package $class;\n  use Carp;\n  sub new {\n";
  87.  
  88.     my $cnt = 0;
  89.     my $idx = 0;
  90.     my( $cmt, $name, $type, $elem );
  91.  
  92.     if( $base_type eq 'HASH' ){
  93.         $out .= "    my(\$r) = {};\n";
  94.         $cmt = '';
  95.     }
  96.     elsif( $base_type eq 'ARRAY' ){
  97.         $out .= "    my(\$r) = [];\n";
  98.     }
  99.     while( $idx < @decls ){
  100.         $name = $decls[$idx];
  101.         $type = $decls[$idx+1];
  102.         push( @methods, $name );
  103.         if( $base_type eq 'HASH' ){
  104.             $elem = "{'$name'}";
  105.         }
  106.         elsif( $base_type eq 'ARRAY' ){
  107.             $elem = "[$cnt]";
  108.             ++$cnt;
  109.             $cmt = " # $name";
  110.         }
  111.         if( $type =~ /^\*(.)/ ){
  112.             $refs{$name}++;
  113.             $type = $1;
  114.         }
  115.         if( $type eq '@' ){
  116.             $out .= "    \$r->$elem = [];$cmt\n";
  117.             $arrays{$name}++;
  118.         }
  119.         elsif( $type eq '%' ){
  120.             $out .= "    \$r->$elem = {};$cmt\n";
  121.             $hashes{$name}++;
  122.         }
  123.         elsif ( $type eq '$') {
  124.             $out .= "    \$r->$elem = undef;$cmt\n";
  125.         }
  126.         elsif( $type =~ /^\w+(?:::\w+)*$/ ){
  127.             $out .= "    \$r->$elem = '${type}'->new();$cmt\n";
  128.             $classes{$name} = $type;
  129.             $got_class = 1;
  130.         }
  131.         else{
  132.             croak "'$type' is not a valid struct element type";
  133.         }
  134.         $idx += 2;
  135.     }
  136.     $out .= "    bless \$r;\n  }\n";
  137.  
  138.  
  139.     my( $pre, $pst, $sel );
  140.     $cnt = 0;
  141.     foreach $name (@methods){
  142.         if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
  143.             carp "function '$name' already defined, overrides struct accessor method"
  144.                 if $^W;
  145.         }
  146.         else {
  147.             $pre = $pst = $cmt = $sel = '';
  148.             if( defined $refs{$name} ){
  149.                 $pre = "\\(";
  150.                 $pst = ")";
  151.                 $cmt = " # returns ref";
  152.             }
  153.             $out .= "  sub $name {$cmt\n    my \$r = shift;\n";
  154.             if( $base_type eq 'ARRAY' ){
  155.                 $elem = "[$cnt]";
  156.                 ++$cnt;
  157.             }
  158.             elsif( $base_type eq 'HASH' ){
  159.                 $elem = "{'$name'}";
  160.             }
  161.             if( defined $arrays{$name} ){
  162.                 $out .= "    my \$i;\n";
  163.                 $out .= "    \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
  164.                 $sel = "->[\$i]";
  165.             }
  166.             elsif( defined $hashes{$name} ){
  167.                 $out .= "    my \$i;\n";
  168.                 $out .= "    \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
  169.                 $sel = "->{\$i}";
  170.             }
  171.             elsif( defined $classes{$name} ){
  172.                 if ( $CHECK_CLASS_MEMBERSHIP ) {
  173.                     $out .= "    croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$type');\n";
  174.                 }
  175.             }
  176.             $out .= "    croak 'Too many args to $name' if \@_ > 1;\n";
  177.             $out .= "    \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
  178.             $out .= "  }\n";
  179.         }
  180.     }
  181.     $out .= "}\n1;\n";
  182.  
  183.     print $out if $print;
  184.     my $result = eval $out;
  185.     carp $@ if $@;
  186. }
  187.  
  188. sub _usage_error {
  189.     confess "struct usage error";
  190. }
  191.  
  192. sub _subclass_error {
  193.     croak 'struct class cannot be a subclass (@ISA not allowed)';
  194. }
  195.  
  196. 1; # for require
  197.  
  198.  
  199. __END__
  200.  
  201. =head1 NAME
  202.  
  203. Class::Struct - declare struct-like datatypes as Perl classes
  204.  
  205. =head1 SYNOPSIS
  206.  
  207.     use Class::Struct;
  208.     struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
  209.     struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
  210.  
  211.     package CLASS_NAME;
  212.     use Class::Struct;
  213.     struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
  214.  
  215.  
  216.     package Myobj;
  217.     use Class::Struct;
  218.     struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
  219.  
  220.     $obj = new Myobj;               # constructor
  221.  
  222.     $element_value = $obj->s;           # element value
  223.     $obj->s('new value');               # assign to element
  224.  
  225.     $ary_ref = $obj->a;                 # reference to whole array
  226.     $ary_element_value = $obj->a(2);    # array element value
  227.     $obj->a(2, 'new value');            # assign to array element
  228.  
  229.     $hash_ref = $obj->h;                # reference to whole hash
  230.     $hash_element_value = $obj->h('x'); # hash element value
  231.     $obj->h('x', 'new value');        # assign to hash element
  232.  
  233.     $element_value = $obj->c;           # object reference
  234.     $obj->c->method(...);               # call method of object
  235.     $obj->c(new My_Other_Class);        # assign a new object
  236.  
  237.  
  238. =head1 DESCRIPTION
  239.  
  240. C<Class::Struct> exports a single function, C<struct>.
  241. Given a list of element names and types, and optionally
  242. a class name, C<struct> creates a Perl 5 class that implements
  243. a "struct-like" data structure.
  244.  
  245. The new class is given a constructor method, C<new>, for creating
  246. struct objects.
  247.  
  248. Each element in the struct data has an accessor method, which is
  249. used to assign to the element and to fetch its value.  The
  250. default accessor can be overridden by declaring a C<sub> of the
  251. same name in the package.  (See Example 2.)
  252.  
  253. Each element's type can be scalar, array, hash, or class.
  254.  
  255.  
  256. =head2 The C<struct()> function
  257.  
  258. The C<struct> function has three forms of parameter-list.
  259.  
  260.     struct( CLASS_NAME => [ ELEMENT_LIST ]);
  261.     struct( CLASS_NAME => { ELEMENT_LIST });
  262.     struct( ELEMENT_LIST );
  263.  
  264. The first and second forms explicitly identify the name of the
  265. class being created.  The third form assumes the current package
  266. name as the class name.
  267.  
  268. An object of a class created by the first and third forms is
  269. based on an array, whereas an object of a class created by the
  270. second form is based on a hash. The array-based forms will be
  271. somewhat faster and smaller; the hash-based forms are more
  272. flexible.
  273.  
  274. The class created by C<struct> must not be a subclass of another
  275. class other than C<UNIVERSAL>.
  276.  
  277. A function named C<new> must not be explicitly defined in a class
  278. created by C<struct>.
  279.  
  280. The I<ELEMENT_LIST> has the form
  281.  
  282.     NAME => TYPE, ...
  283.  
  284. Each name-type pair declares one element of the struct. Each
  285. element name will be defined as an accessor method unless a
  286. method by that name is explicitly defined; in the latter case, a
  287. warning is issued if the warning flag (B<-w>) is set.
  288.  
  289.  
  290. =head2 Element Types and Accessor Methods
  291.  
  292. The four element types -- scalar, array, hash, and class -- are
  293. represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
  294. optionally preceded by a C<'*'>.
  295.  
  296. The accessor method provided by C<struct> for an element depends
  297. on the declared type of the element.
  298.  
  299. =over
  300.  
  301. =item Scalar (C<'$'> or C<'*$'>)
  302.  
  303. The element is a scalar, and is initialized to C<undef>.
  304.  
  305. The accessor's argument, if any, is assigned to the element.
  306.  
  307. If the element type is C<'$'>, the value of the element (after
  308. assignment) is returned. If the element type is C<'*$'>, a reference
  309. to the element is returned.
  310.  
  311. =item Array (C<'@'> or C<'*@'>)
  312.  
  313. The element is an array, initialized to C<()>.
  314.  
  315. With no argument, the accessor returns a reference to the
  316. element's whole array.
  317.  
  318. With one or two arguments, the first argument is an index
  319. specifying one element of the array; the second argument, if
  320. present, is assigned to the array element.  If the element type
  321. is C<'@'>, the accessor returns the array element value.  If the
  322. element type is C<'*@'>, a reference to the array element is
  323. returned.
  324.  
  325. =item Hash (C<'%'> or C<'*%'>)
  326.  
  327. The element is a hash, initialized to C<()>.
  328.  
  329. With no argument, the accessor returns a reference to the
  330. element's whole hash.
  331.  
  332. With one or two arguments, the first argument is a key specifying
  333. one element of the hash; the second argument, if present, is
  334. assigned to the hash element.  If the element type is C<'%'>, the
  335. accessor returns the hash element value.  If the element type is
  336. C<'*%'>, a reference to the hash element is returned.
  337.  
  338. =item Class (C<'Class_Name'> or C<'*Class_Name'>)
  339.  
  340. The element's value must be a reference blessed to the named
  341. class or to one of its subclasses. The element is initialized to
  342. the result of calling the C<new> constructor of the named class.
  343.  
  344. The accessor's argument, if any, is assigned to the element. The
  345. accessor will C<croak> if this is not an appropriate object
  346. reference.
  347.  
  348. If the element type does not start with a C<'*'>, the accessor
  349. returns the element value (after assignment). If the element type
  350. starts with a C<'*'>, a reference to the element itself is returned.
  351.  
  352. =back
  353.  
  354. =head1 EXAMPLES
  355.  
  356. =over
  357.  
  358. =item Example 1
  359.  
  360. Giving a struct element a class type that is also a struct is how
  361. structs are nested.  Here, C<timeval> represents a time (seconds and
  362. microseconds), and C<rusage> has two elements, each of which is of
  363. type C<timeval>.
  364.  
  365.     use Class::Struct;
  366.  
  367.     struct( rusage => {
  368.         ru_utime => timeval,  # seconds
  369.         ru_stime => timeval,  # microseconds
  370.     });
  371.  
  372.     struct( timeval => [
  373.         tv_secs  => '$',
  374.         tv_usecs => '$',
  375.     ]);
  376.  
  377.     my $t = new rusage;
  378.  
  379.     $t->ru_utime->tv_secs(100);
  380.     $t->ru_utime->tv_usecs(0);
  381.     $t->ru_stime->tv_secs(5);
  382.     $t->ru_stime->tv_usecs(0);
  383.  
  384.  
  385. =item Example 2
  386.  
  387. An accessor function can be redefined in order to provide
  388. additional checking of values, etc.  Here, we want the C<count>
  389. element always to be nonnegative, so we redefine the C<count>
  390. accessor accordingly.
  391.  
  392.     package MyObj;
  393.     use Class::Struct;
  394.  
  395.     struct ( 'MyObj', { count => '$', stuff => '%' } );
  396.  
  397.     sub count {
  398.         my $self = shift;
  399.         if ( @_ ) {
  400.             die 'count must be nonnegative' if $_[0] < 0;
  401.             $self->{'count'} = shift;
  402.             warn "Too many args to count" if @_;
  403.         }
  404.         return $self->{'count'};
  405.     }
  406.  
  407.     package main;
  408.     $x = new MyObj;
  409.     print "\$x->count(5) = ", $x->count(5), "\n";
  410.  
  411.     print "\$x->count = ", $x->count, "\n";
  412.  
  413.     print "\$x->count(-5) = ", $x->count(-5), "\n";
  414.  
  415.  
  416. =head1 Author and Modification History
  417.  
  418.  
  419. Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
  420.  
  421.     members() function removed.
  422.     Documentation corrected and extended.
  423.     Use of struct() in a subclass prohibited.
  424.     User definition of accessor allowed.
  425.     Treatment of '*' in element types corrected.
  426.     Treatment of classes as element types corrected.
  427.     Class name to struct() made optional.
  428.     Diagnostic checks added.
  429.  
  430.  
  431. Originally C<Class::Template> by Dean Roehrich.
  432.  
  433.  
  434. =cut
  435.